package model;

import java.beans.XMLDecoder;
import java.beans.XMLEncoder;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;

import javax.swing.table.AbstractTableModel;

import entity.Notiz;

public class NotizManagement extends AbstractTableModel {

	private static final long serialVersionUID = 3135491780602833440L;
	private String[] titel = {"Nr.", "Aufgabe"};
	private List<Notiz> notizen;
	private static final String DATEI="aufgaben.xml";

	public NotizManagement(){
		notizen = new ArrayList<Notiz>();
		laden();
	}
	
	@Override
	public int getColumnCount() {
		return 2;
	}

	@Override
	public int getRowCount() {
		return notizen.size();
	}

	@Override
	public Object getValueAt(int row, int col) {
		Notiz n = notizen.get(row);
		switch(col){
		case 0:
			return n.getId();
		case 1:
			return n.getText();
		}
		return null;
	}
	
	 @Override
	 public void setValueAt( Object val, int row, int column ){
		 if (val.toString().trim().equals(""))
			 notizLoeschen(row);
		 else
			 notizAendern(row,val.toString());
	 }

	
	@Override
	public String getColumnName( int colIndex ){
		return titel[colIndex];
	}
	
	@Override
	public boolean isCellEditable(int rowIndex, int colIndex ){
		return colIndex>0;
	}
	
	private void inform(){
		this.fireTableDataChanged();
	}
	
	public void notizHinzufuegen(String text){
		notizen.add(0,new Notiz(text));
		inform();
	}
	
	public void notizLoeschen(int pos){
		notizen.remove(pos);
		inform();
	}
	
	public void notizAendern(int pos, String text){
		notizen.get(pos).setText(text);
		inform();
	}

	public void speichern() {
		   XMLEncoder out = null;
		    try {
		      out = new XMLEncoder(new BufferedOutputStream(
		                           new FileOutputStream(DATEI)));
		      out.writeObject(notizen);
		    } catch (FileNotFoundException e) {// unsauberst
		    } finally {
		      out.close();
		    }	
	}

	@SuppressWarnings("unchecked")
	public void laden() {
		XMLDecoder in = null;
	    try {
	      in = new XMLDecoder(new BufferedInputStream(
	          new FileInputStream(DATEI)));
	      notizen = ((ArrayList<Notiz>) in.readObject());
	      inform();
	      berechneMaxID();
	    } catch (Exception e) {// unsauberst
	    } finally {
	    	if(in!=null)	
	    		in.close();
	    }	
	}
	
	private void berechneMaxID(){
		int max = 0;
		for(Notiz n:notizen)
			if (max<n.getId())
				max = n.getId();
		Notiz.setzeNEXTID(max+1);
	}

}
